package com.yazi.mxz.common.service.impl;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.myframework.smhj.common.exception.MyEntityNotExistsException;
import com.myframework.smhj.common.exception.MyException;
import com.myframework.smhj.common.exception.MyNoPermissionException;
import com.myframework.smhj.hibernate.dao.BasicService;
import com.myframework.smhj.hibernate.dao.Dao;
import com.yazi.mxz.common.MyUtil;
import com.yazi.mxz.common.db.dao.OrderDao;
import com.yazi.mxz.common.db.dao.OrderGoodsDao;
import com.yazi.mxz.common.entity.beans.Order;
import com.yazi.mxz.common.entity.beans.OrderGoods;
import com.yazi.mxz.common.entity.beans.Store;
import com.yazi.mxz.common.entity.enums.OrderStatus;
import com.yazi.mxz.common.service.OrderGoodsService;

@Service("orderGoodsService")
public class OrderGoodsServiceImpl extends BasicService<OrderGoods> implements OrderGoodsService {
	private static Logger log = LoggerFactory.getLogger(OrderGoodsServiceImpl.class);

	@Resource
	OrderGoodsDao orderGoodsDao;
	@Resource
	OrderDao orderDao;
	
	@Override
	protected Dao<OrderGoods> getDao() {
		return orderGoodsDao;
	}
	
	@Override
	public void editCostByStore(Store store, long orderId, long orderGoodsId, float realCost) throws MyException {
		log.debug("modifyCostByStore：storeId={},orderId={},orderGoodsId={},realCost={}", 
				new Object[]{store.getStoreId(), orderId, orderGoodsId, realCost});
		
		Order order = orderDao.get(orderId);
		if (null == order) {
			throw new MyEntityNotExistsException();
		}
		if (order.getStatus() != OrderStatus.NEW.ordinal()) {
			throw new MyNoPermissionException("订单当前状态不允许此操作");
		}
		if (!order.getStore().equals(store)) {
			throw new MyNoPermissionException();
		}
		
		OrderGoods orderGoods = orderGoodsDao.get(orderGoodsId);
		if (null == orderGoods) {
			throw new MyEntityNotExistsException();
		}
		if (!orderGoods.getOrder().equals(order)) {
			throw new MyNoPermissionException();
		}
		
		// 更新订单费用
		order.setRealCost(MyUtil.numRoundDown(order.getRealCost() - orderGoods.getRealCost() + realCost, 2).floatValue());// 钱算少了
		orderDao.merge(order);
		
		// 更新订单商品费用及购买量
		orderGoods.setRealCount(MyUtil.numRoundDown(realCost/orderGoods.getPrice(), 2).floatValue());// 量算少了
		orderGoods.setRealCost(MyUtil.numRoundDown(realCost, 2).floatValue());// 钱算少了
		orderGoodsDao.merge(orderGoods);
		
	}
	
}
